//
//  RecordCutViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "RecordCutViewController.h"
#import "SeeAudio.h"
#import "AVPlayerManager.h"
#import "CustomLineView.h"
#import "UIView_extension.h"
#import "LFVideoTrimmerGridView.h"
#import "LFSpectrumTrimmerGridView.h"
#import "RecordEditSpectrumView.h"
#import "EZAudioFile.h"
#import "FileManager.h"
#import "CustomAlertView.h"
#import "LocalRecordModel.h"

@interface RecordCutViewController ()<AVPlayerDelegate, UIScrollViewDelegate, LFVideoTrimmerGridViewDelegate, LFSpectrumTrimmerGridViewDelegate, UIGestureRecognizerDelegate> {
    CGFloat duration;
    CGFloat currentTime;
    CGFloat spectrumGridWidth;
    BOOL isDragging;
    LFSpectrumTrimmerGridView *spectrumGrid;
    LFVideoTrimmerGridView *exampleGrid;
    RecordEditSpectrumView *selectedSpectrumView;
    
}
@property (weak, nonatomic) IBOutlet UIImageView *bg;
@property (weak, nonatomic) IBOutlet UIScrollView *waveScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *actionBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (nonatomic, strong) EZAudioFile *audioFile;
@property (nonatomic, strong) CustomLineView *line;

@end

@implementation RecordCutViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"截取";
    [self addBackBtn];
    [((UIButton *)[self addRigthBtn:@"完成"]) addTarget:self action:@selector(donePress) forControlEvents:UIControlEventTouchUpInside];
    [self initView];
    [self showSpectrumView];
    
    /** 时间轴 */
    exampleGrid = [[LFVideoTrimmerGridView alloc] initWithFrame:CGRectMake(16, 192, SCREEN_WIDTH_DEVICE - 32, 60)];
    exampleGrid.delegate = self;
    [self.scrollView addSubview:exampleGrid];
    if (self.model.needSaveUrl) {
        self.audioFile = [EZAudioFile audioFileWithURL:self.model.needSaveUrl];
    } else {
        NSString *path = [[FileManager sharedManager] getLocalFilePath:self.model.fileName];
        if ([[FileManager sharedManager] judgeObjectExistence:path] && [[NSData dataWithContentsOfFile:path] length] > 0) {
            self.audioFile = [EZAudioFile audioFileWithURL:[NSURL fileURLWithPath:path]];
        } else {
            self.audioFile = nil;
        }
    }
    

    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [AVPlayerManager manager].delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[AVPlayerManager manager] pause];
    [AVPlayerManager manager].delegate = nil;

}

- (void)donePress {
    if (self.ReloadHandle) {
        self.ReloadHandle(self.audioFile.url, self.title);
    }
    [self goBackAction];
}


- (IBAction)deletePress {
    CustomAlertView *alertView = [[CustomAlertView alloc] initItem:@"确定要删除该音频？" withButtons:[NSArray arrayWithObjects:@"取消", @"确定", nil]];
    alertView.SureHandle = ^{
        if (self.DeleteHandle) {
            self.DeleteHandle(self.model);
        }
    };
    [alertView backgroundClickDisable];
    [alertView show];
}

- (IBAction)actionPress {
    self.actionBtn.selected = !self.actionBtn.selected;
    if (!self.actionBtn.selected) {
        [[AVPlayerManager manager] pause];
    } else {
        [[AVPlayerManager manager] play];
    }
}

- (IBAction)cutPress {
    [[AVPlayerManager manager] pause];
    self.actionBtn.selected = NO;
    [self loadingHUDAlert];
    CGFloat startTime = spectrumGrid.gridRect.origin.x/spectrumGridWidth*self.audioFile.duration;
    CGFloat endTime = spectrumGrid.gridRect.size.width/spectrumGridWidth*self.audioFile.duration+startTime;
    [AVPlayerManager cutAudioStartTime:startTime endTime:endTime withPath:[self.audioFile.url absoluteString] completed:^(NSString *successPath) {
        self.audioFile = [EZAudioFile audioFileWithURL:[NSURL fileURLWithPath:successPath]];
        [self seeAudio:self.audioFile.url];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self->selectedSpectrumView refreshTime:self.audioFile.formattedDuration];
            [self.waveScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            self->exampleGrid.gridRect = CGRectMake(0, 0, SCREEN_WIDTH_DEVICE - 32, 60);
        });
        
    }];
}

- (void)seeAudio:(NSURL *)url {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.waveScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    });
    [[AVPlayerManager manager] setAVPlayerURL:url];
    AVURLAsset  *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    self->duration = CMTimeGetSeconds(asset.duration);
    __weak __typeof(self) weakSelf = self;
    [SeeAudio renderPNGAudioPictogramLogForAsset:asset done:^(UIImage *spectrumImage,UIImage *scaleImage,NSInteger imageWidth) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHudAlert];
            [weakSelf.waveScrollView setContentSize:CGSizeMake(imageWidth, 0)];
            UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imageWidth, 280)];
            imgv.image = spectrumImage;
            [weakSelf.waveScrollView addSubview:imgv];
            UIImageView *scaleImgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 280, imageWidth, 30)];
            scaleImgv.image = scaleImage;
            [weakSelf.waveScrollView addSubview:scaleImgv];
            
            self->spectrumGridWidth = imageWidth-SCREEN_WIDTH_DEVICE;
            self->spectrumGrid = [[LFSpectrumTrimmerGridView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH_DEVICE/2.0, 0, imageWidth-SCREEN_WIDTH_DEVICE, 280)];
            self->spectrumGrid.delegate = self;
            [weakSelf.waveScrollView addSubview:self->spectrumGrid];
        });
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    isDragging = YES;
    [[AVPlayerManager manager] pause];
    self.actionBtn.selected = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    isDragging = NO;
    [[AVPlayerManager manager] seekToTimeInterval:currentTime];

//    [[AVPlayerManager manager] play];
//    self.actionBtn.selected = YES;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [[AVPlayerManager manager] seekToTimeInterval:currentTime];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.waveScrollView == scrollView) {
        currentTime = (scrollView.contentOffset.x/(scrollView.contentSize.width-SCREEN_WIDTH_DEVICE))*duration;
        if (currentTime > duration) {
            currentTime = duration;
        } else if (currentTime <= 0) {
            currentTime = 0;
        }
        int currentMin  = (int)currentTime / 60;
        int currentSecond  = (int)currentTime % 60;
        int millisecond = (currentTime - currentSecond)*100 - currentMin*60*100;
        NSString *currentTime1 = [NSString stringWithFormat:@"%.2d:%.2d.%02d",currentMin,currentSecond, millisecond];
        self.timeLabel.text = currentTime1;
    }
}

#pragma mark ---AVPlayerDelegate---
- (void)timeRunAndTime:(double)runTime andValue:(NSString *)value andScale:(CGFloat)scale {
    currentTime = runTime;
    self.timeLabel.text = value;
    if ([AVPlayerManager manager].isPlaying) {
        CGFloat pointX = (self.waveScrollView.contentSize.width-SCREEN_WIDTH_DEVICE)*scale;
        if (pointX < self.waveScrollView.contentOffset.x) {
            pointX = self.waveScrollView.contentOffset.x;
        }
        [UIView animateWithDuration:0.1 animations:^{
            [self.waveScrollView setContentOffset:CGPointMake(pointX, 0) animated:NO];
        }];
    }
}

- (void)trackPlayDidEnd {
    self.actionBtn.selected = NO;
    [self.waveScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark - LFVideoTrimmerGridViewDelegate
- (void)lf_videoTrimmerGridViewDidBeginResizing:(LFVideoTrimmerGridView *)gridView {
    NSLog(@"============%f", gridView.gridRect.size.width/(SCREEN_WIDTH_DEVICE - 32));
    [self updateSpectrumGridFrame:gridView];
}
- (void)lf_videoTrimmerGridViewDidResizing:(LFVideoTrimmerGridView *)gridView {
    NSLog(@"============%f", gridView.gridRect.size.width/(SCREEN_WIDTH_DEVICE - 32));
    [self updateSpectrumGridFrame:gridView];
}
- (void)lf_videoTrimmerGridViewDidEndResizing:(LFVideoTrimmerGridView *)gridView {
    NSLog(@"============%f", gridView.gridRect.size.width/(SCREEN_WIDTH_DEVICE - 32));
    [self updateSpectrumGridFrame:gridView];
}

- (void)updateExampleGridFrame:(LFSpectrumTrimmerGridView *)gridView {
    CGRect rect = exampleGrid.gridRect;
    rect.origin.x = ((gridView.gridRect.origin.x/spectrumGridWidth)*(SCREEN_WIDTH_DEVICE-32));
    rect.size.width = (gridView.gridRect.size.width/spectrumGridWidth)*(SCREEN_WIDTH_DEVICE-32);
    exampleGrid.gridRect = rect;
}

#pragma mark - LFSpectrumTrimmerGridViewDelegate
- (void)lf_spectrumTrimmerGridViewDidBeginResizing:(LFSpectrumTrimmerGridView *)gridView {
    NSLog(@"============%f", gridView.gridRect.size.width/spectrumGridWidth);
    [self updateExampleGridFrame:gridView];
}
- (void)lf_spectrumTrimmerGridViewDidResizing:(LFSpectrumTrimmerGridView *)gridView {
    NSLog(@"============%f", gridView.gridRect.size.width/spectrumGridWidth);
    [self updateExampleGridFrame:gridView];

}
- (void)lf_spectrumTrimmerGridViewDidEndResizing:(LFSpectrumTrimmerGridView *)gridView {
    NSLog(@"============%f", gridView.gridRect.size.width/spectrumGridWidth);
    [self updateExampleGridFrame:gridView];
}

- (void)updateSpectrumGridFrame:(LFVideoTrimmerGridView *)gridView {
    CGRect rect = spectrumGrid.gridRect;
    rect.origin.x = ((gridView.gridRect.origin.x/(SCREEN_WIDTH_DEVICE-32))*spectrumGridWidth);
    rect.size.width = (gridView.gridRect.size.width/(SCREEN_WIDTH_DEVICE - 32))*spectrumGridWidth;
    spectrumGrid.gridRect = rect;
}

- (void)initView {
    [self.bg setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 280, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - (IS_iPhoneX_Top + NavBarHeight + 280))];
    [self.scrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 310, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Bottom - IS_iPhoneX_Top - NavBarHeight - 50 - 310)];
    [self.scrollView setContentSize:CGSizeMake(0, 300)];
    [self.waveScrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, 310)];
    [self.view addSubview:self.line];
}

- (void)showSpectrumView {
    selectedSpectrumView = [[RecordEditSpectrumView alloc] initCustomView:CGRectMake(16, 192, SCREEN_WIDTH_DEVICE - 32, 85) index:0 recordModel:self.model];
    [self.scrollView addSubview:selectedSpectrumView];
    [self seeAudio:selectedSpectrumView.audioFile.url];
    
//    if (self.contentArr.count == 1) {
        
//    } else {
//        CGFloat originX = 16;
//        CGFloat originY = 0;
//        CGFloat width = 122;
//        CGFloat height = 85;
//        for (NSInteger i = 0; i < self.contentArr.count; i++) {
//            RecordEditSpectrumView *itemView = [[RecordEditSpectrumView alloc] initCustomView:CGRectMake(originX, originY, width, height) index:i+1 recordModel:[self.contentArr objectAtIndex:i]];
//            itemView.OnClickHandle = ^(RecordEditSpectrumView * _Nonnull itemViewEx) {
//                if (itemViewEx != self->selectedSpectrumView) {
//                    [self->selectedSpectrumView cancelSelected];
//                    self->selectedSpectrumView = itemViewEx;
//                    [self seeAudio:itemViewEx.audioFile.url];
//                }
//            };
//            [self.spectrumScrollView addSubview:itemView];
//            originX += width + 10;
//            if (i == 0) {
//                [itemView setSelected];
//                selectedSpectrumView = itemView;
//                [self seeAudio:itemView.audioFile.url];
//            }
//        }
//        [self.spectrumScrollView setContentSize:CGSizeMake(originX + 6, 0)];
//    }
}

- (CustomLineView *)line {
    if (!_line) {
        _line = [[CustomLineView alloc] initCustomView:CGRectMake((SCREEN_WIDTH_DEVICE-3)/2.0, IS_iPhoneX_Top + NavBarHeight, 3, 280)];
    }
    return _line;
}
@end
